<template>
  <div class="app-container">
    <el-col :span="collapse_span_l" :xs="24">
      <div class="head-container">
        <el-input
          v-model="resourcesClassName"
          placeholder="请输入分类名称"
          clearable
          size="small"
          prefix-icon="el-icon-search"
          style="margin-bottom: 20px"
        />
      </div>
      <div class="head-container" style="margin-bottom:10px">
        <el-button
          icon="el-icon-plus"
          type="text"
          size="mini"
          v-hasPermi="['pub:resourcesClass:add']"
          @click="addTree()"
        ></el-button>&nbsp;
        <el-button
          icon="el-icon-edit"
          type="text"
          size="mini"
          v-hasPermi="['pub:resourcesClass:edit']"
          @click="editTree()"
        ></el-button>&nbsp;
        <el-button
          icon="el-icon-delete"
          type="text"
          size="mini"
          v-hasPermi="['pub:resourcesClass:remove']"
          @click="removeTree()"
        ></el-button>&nbsp;
        <el-button icon="el-icon-refresh" type="text" size="mini" @click="getTreeSelect()"></el-button>
      </div>
      <div class="head-container">
        <el-tree
          v-loading="treeLoading"
          highlight-current
          node-key="id"
          :data="resourcesClassTreeOptions"
          :props="defaultProps"
          :expand-on-click-node="false"
          :filter-node-method="filterNode"
          ref="tree"
          default-expand-all
          @node-click="handleNodeClick"
        >
          <span class="custom-tree-node" slot-scope="{ node, data }"  >
            <span :title="node.label + '(' +data.id+ ')'">{{ node.label }}</span>
          </span>
        </el-tree>
      </div>
    </el-col>
    <el-col :span="1" :xs="24">
      <div class="collapse" :style="{'margin-left': ml + 'px'}">
        <div class="collapse_center" v-show="collapse_span_l == 3" @click="handleFold">
          <i class="el-icon-caret-left collapse_icon"></i>
        </div>
        <div class="collapse_center" v-show="collapse_span_l == 0" @click="handleUnfold">
          <i class="el-icon-caret-right collapse_icon"></i>
        </div>
      </div>
    </el-col>
    <el-col :span="collapse_span_r" :xs="24">
      <el-form @submit.native.prevent
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        v-show="showSearch"
        label-width="70px"
      >
        <el-form-item label="资源名" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入资源名"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col>
          <uploaderBig :resourcesClass="resourcesClass" v-if="resourcesClass" v-hasPermi="['pub:resources:add']" @uploadSuccess="uploadSuccess"/>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="resourcesList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主键id" align="center" prop="id" />
        <el-table-column label="资源名" align="center" prop="name" />
<!--        <el-table-column label="资源分类id" align="center" prop="resourcesClassId" />-->
        <el-table-column label="文件夹路径" align="center" prop="dirPath" :show-overflow-tooltip='true'/>
<!--        <el-table-column label="文件路径" align="center" prop="filePath" />-->
        <el-table-column label="文件URL" align="center" prop="fileUrl" min-width="250%" >
          <template slot-scope="scope">
            {{scope.row.fileUrl}}
            <el-link :underline="false" icon="el-icon-document-copy" v-clipboard:copy="scope.row.fileUrl" v-clipboard:success="clipboardSuccess" style="float:right">复制</el-link>
          </template>
        </el-table-column>
        <el-table-column label="图片预览" align="center" prop="fileUrl" >
          <template slot-scope="scope" v-if="isImage(scope.row.fileType)">
            <image-preview :src="scope.row.fileUrl" :width="50" :height="50"/>
          </template>
        </el-table-column>
        <el-table-column label="文件类型" align="center" prop="fileType" />
        <el-table-column label="文件大小" align="center" prop="fileSize" >
          <template slot-scope="scope">
            <span>{{ formatBytes(scope.row.fileSize,2) }}</span>
          </template>
        </el-table-column>
<!--        <el-table-column label="存储类型" align="center" prop="storageType" />-->
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['pub:resources:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-col>

    <!-- 添加或修改资源分类管理对话框 -->
    <el-dialog
      v-dialogDrag
      :title="resourcesClassTitle"
      :visible.sync="openResourcesClass"
      :close-on-click-modal="false"
      width="500px"
      append-to-body
    >
      <el-form
        ref="resourcesClassForm"
        :model="resourcesClassForm"
        :rules="resourcesClassRules"
        label-width="80px"
      >
        <el-form-item label="父级资源分类" label-width="120px" prop="parentId">
          <treeselect
            v-model="resourcesClassForm.parentId"
            :options="resourcesClassOptions"
            :normalizer="normalizer"
            placeholder="请选择父资源分类"
          />
        </el-form-item>
        <el-form-item label="资源分类名称" label-width="120px" prop="name">
          <el-input v-model="resourcesClassForm.name" placeholder="请输入资源分类名称" />
        </el-form-item>
        <el-form-item label="排序" label-width="120px" prop="orderNum">
          <el-input type="number" v-model="resourcesClassForm.orderNum" placeholder="排序" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormResourcesClass">确 定</el-button>
        <el-button @click="cancelResourcesClass">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listResources,
  getResources,
  delResources,
  addResources,
  updateResources,
  exportResources,
  uploadFile,
  addOrUpdate
} from "@/api/pub/resources";
import {
  listResourcesClass,
  getResourcesClass,
  delResourcesClass,
  addResourcesClass,
  updateResourcesClass,
  exportResourcesClass,
  treeSelect
} from "@/api/pub/resourcesClass";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import uploaderBig from "./uploaderBig";

export default {
  name: "Resources",
  components: {
    Treeselect,
    uploaderBig
  },
  data() {
    return {
      treeData: null,
      resourcesClass: null,
      resourcesClassTitle: "",
      resourcesClassTreeOptions: [],
      resourcesClassName: undefined,
      // 部门树选项
      defaultProps: {
        children: "children",
        label: "label"
      },
      openResourcesClass: false,
      // 批量上传表单数组
      forms: [],
      // 资源分类添加/修改表单
      resourcesClassForm: {},
      // 上传文件设置请求头
      headers: { "Content-Type": "multipart/form-data" },
      // 资源目录的domainurl
      dirDomainUrl: "",
      // 修改资源时,用来保存资源旧的绝对路径
      oldFilePath: "",
      // 资源修改时,标志是否修改了路径
      changePathFlag: false,
      // 资源修改时,标志是否修改了资源文件
      changeFileFlag: false,
      // 标志是否打开了修改页面
      updateFlag: false,
      // 遮罩层
      loading: true,
      treeLoading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 资源表格数据
      resourcesList: [],
      // 资源分类集合
      resourcesClassOptions: [],
      // 目录集合
      directoryOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      fileList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        resourcesClassId: null,
        resourcesClassName: null,
        fileType: null,
        description: null
      },
      // 表单参数
      form: {},
      resourcesClassRules: {
        name: [
          { required: true, message: "分类名称不能为空", trigger: "blur" }
        ],
        delFlag: [
          { required: true, message: "删除标志不能为空", trigger: "blur" }
        ],
        tenantId: [
          { required: true, message: "租户id不能为空", trigger: "blur" }
        ]
      },
      collapse_span_l: 3,
      collapse_span_r: 20,
      ml: 20
    };
  },
  created() {
    this.getTreeSelect();
    this.getList();
  },
  watch: {
    // 根据名称筛选栏目树
    resourcesClassName(val) {
      this.$refs.tree.filter(val);
    }
  },
  methods: {
    resourcesClassFormReset() {
      this.resourcesClassForm = {
        id: null,
        name: null,
        parentId: null,
        parentName: null,
        ancestors: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        tenantId: null
      };
      this.resetForm("resourcesClassForm");
    },

    addTree() {
      if (this.treeData) {
        var data = this.treeData;
      }
      this.resourcesClassFormReset();
      this.getResourcesClassListInAdd();
      if (data != null) {
        this.resourcesClassForm.parentId = data.id;
      }
      this.openResourcesClass = true;
      this.resourcesClassTitle = "添加资源分类管理";
    },
    editTree() {
      if (this.treeData) {
        var data = this.treeData;
      } else {
        this.$message({
          message: "请选择分类",
          type: "warning"
        });
        return;
      }
      this.resourcesClassFormReset();
      this.getResourcesClassListInAdd();
      this.openResourcesClass = true;
      if (data != null) {
        this.resourcesClassForm.parentId = data.id;
      }
      getResourcesClass(data.id).then(response => {
        this.resourcesClassForm = response.data;
        this.openResourcesClass = true;
        this.resourcesClassTitle = "修改资源分类管理";
      });
    },
    removeTree() {
      if (this.treeData) {
        var data = this.treeData;
      } else {
        this.$message({
          message: "请选择分类",
          type: "warning"
        });
        return;
      }
      this.$confirm(
        '是否确认删除资源分类名称为"' + data.label + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(function() {
          return delResourcesClass(data.id);
        })
        .then(() => {
          this.treeData = null;
          this.getTreeSelect();
          this.msgSuccess("删除成功");
        })
        .catch(function() {});
    },
    // 取消按钮
    cancelResourcesClass() {
      this.openResourcesClass = false;
    },
    submitFormResourcesClass() {
      this.$refs["resourcesClassForm"].validate(valid => {
        if (valid) {
          if (this.resourcesClassForm.id != null) {
            updateResourcesClass(this.resourcesClassForm).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.openResourcesClass = false;
                this.getTreeSelect();
              }
            });
          } else {
            addResourcesClass(this.resourcesClassForm).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.openResourcesClass = false;
                this.getTreeSelect();
              }
            });
          }
        }
      });
    },
    /** 查询左侧栏目下拉树结构 */
    getTreeSelect() {
      this.treeLoading = true;
      treeSelect().then(response => {
        //console.log('treeSelect',response);
        this.treeLoading = false;
        let data = [
          {
            id: 0,
            label: "全部",
            children: response.data
          }
        ];
        this.resourcesClassTreeOptions = data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1 || String(data.id) === value;
    },
    // 节点单击事件
    handleNodeClick(data) {
      //console.log('handleNodeClick',data);
      if(data.treeEntity){
        this.resourcesClass = data.treeEntity;
      }else{
        this.resourcesClass = null;
      }
      this.treeData = data;
      this.queryParams.resourcesClassId = data.id;
      this.getList();
    },

    /** 查询资源列表 */
    getList() {
      this.loading = true;
      listResources(this.queryParams).then(response => {
        this.resourcesList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        resourcesClassId: null,
        dirPath: null,
        filePath: null,
        fileUrl: null,
        fileType: null,
        fileSize: null,
        storageType: null,
        createBy: null,
        createId: null,
        createTime: null,
        updateBy: null,
        updateId: null,
        updateTime: null,
        delFlag: null,
        remark: null,
        tenantId: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除资源?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return delResources(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(function() {});
    },
    /** 查询资源分类列表*/
    getResourcesClassList() {
      listResourcesClass().then(response => {
        // todo 如果资源分类为空,需要先添加资源分类再添加资源
        if (this.isEmptyArray(response.data)) {
          this.$message.error("资源分类为空,请先添加资源分类!");
        }
        this.resourcesClassOptions = [];
        this.resourcesClassOptions = this.handleTree(
          response.data,
          "id",
          "parentId"
        );
      });
    },
    /** 查询资源分类列表*/
    getResourcesClassListInAdd() {
      listResourcesClass().then(response => {
        this.resourcesClassOptions = [];
        const data = { id: 0, name: "全部", children: [] };
        data.children = this.handleTree(response.data, "id", "parentId");
        this.resourcesClassOptions.push(data);
      });
    },
    // 转换树结构
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },
    /** 查询目录列表
    getDirectoryList() {
      listDirectory().then(response => {
        // todo 如果目录为空,需要先添加目录再添加资源
        if (this.isEmptyArray(response.data)) {
          this.$message.error("目录为空,请先添加目录!");
        }
        this.directoryOptions = [];
        const data = { id: 0, path: "顶级节点", children: [] };
        data.children = this.handleTree(response.data, "id", "parentId");
        this.directoryOptions.push(data);
      });
    },*/
    normalizerDir(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.path,
        children: node.children
      };
    },
    // 获得资源分类名称
    getResourcesClassName(node) {
      this.form.resourcesClassName = node.name;
    },
    // 获得目录路径和domainurl
    getResourcesDirPath(node) {
      this.form.resourcesDirPath = node.absolutePath;
      this.dirDomainUrl = node.domainUrl;
      // 判断是否修改了路径
      if (node.absolutePath != this.oldFilePath) {
        this.changePathFlag = true;
      }
    },
    // 判断数组是否为空
    isEmptyArray(arrayTemp) {
      return arrayTemp.length == 0;
    },
    // 栏目折叠
    handleFold() {
      this.collapse_span_l = 0;
      this.collapse_span_r = 23;
      this.ml = 0;
    },
    // 栏目展开
    handleUnfold() {
      this.collapse_span_l = 3;
      this.collapse_span_r = 20;
      this.ml = 20;
    },
    // a 参数：表示要被转化的容量大小，以字节为单
    // b 参数：表示如果转换时出小数，四舍五入保留多少位 默认为2位小数
    formatBytes(a, b) {
      if (0 == a) return "0 B";
      var c = 1024, d = b || 2, e = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"], f = Math.floor(Math.log(a) / Math.log(c));
      return parseFloat((a / Math.pow(c, f)).toFixed(d)) + " " + e[f];
    },
    isImage(fileType) {
      return fileType.startsWith('image/');
    },
    /** 复制代码成功 */
    clipboardSuccess() {
      this.$modal.msgSuccess("复制成功");
    },
    // 上传回调
    uploadSuccess(resource){
      console.log(resource)
      addOrUpdate(resource).then(res=>{
        this.$modal.msgSuccess(resource.name + " 文件上传成功!");
        this.getList();
      });
    },
  }
};
</script>
<style>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
.collapse {
  position: relative;
  width: 15px;
  height: 691px;
  background: #fafafa;
}
.collapse_center {
  position: absolute;
  top: 320px;
  left: 0;
  width: 15px;
  height: 50px;
  background: #eee;
}
.collapse_center:hover {
  background: #1890ff;
  color: #ffffff;
}
.collapse_icon {
  margin-top: 17px;
}
</style>

